package com.bot.snakeRunningSystem.pool;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SnakePool extends Thread{
    private final static ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private Queue<Snake> snakeQueue = new LinkedList<>();

    public void addSnakeToSnakeQueue(Integer userId, String snakeCode, String input) {
        lock.lock();
        try {
            snakeQueue.add(new Snake(userId, snakeCode, input));
            condition.signalAll(); // 唤醒消费者
        } finally {
            lock.unlock();
        }
    }

    // 消费该任务
    private void consumeSnake(Snake snake) {
        Consumer consumer = new Consumer();
        consumer.startTimeout(2000, snake);

    }

    @Override
    public void run() {
        // 生产者往里面加Snake, 消费者消费Snake所以会存在读写冲突
        while (true) {
            lock.lock();
            if (snakeQueue.isEmpty()) {
                // 阻塞消费者队列
                try {
                    condition.await(); // 阻塞线程，释放锁

                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            } else {
                Snake snake = snakeQueue.remove();
                lock.unlock();
                this.consumeSnake(snake); // 比较耗时，可能会执行几秒
            }
        }
    }
}
